﻿using Peninsula.Common.Log;
using Peninsula.Site.Data.Constant;
using Peninsula.Utility.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.ModelBinding;


namespace Peninsula.Site.Data.Result
{
    public static class ApiJsonResultDataExtensions
    {

        public static ILogger Logger { set; private get; }

        public static void SetCodeMsg(this ApiJsonResultData json, int code)
        {
            json.code = code;
            json.msg = ErrorCodes.CodeMsgDict[code];
        }


        public static void SetModelValidErrorMessage(this ApiJsonResultData jsonResultEntry, ModelStateDictionary dictionary)
        {
            List<string> msgs = new List<string>();
            foreach (var kv in dictionary)
            {
                foreach (var err in kv.Value.Errors)
                {
                    msgs.Add(err.ErrorMessage);
                }
            }
            jsonResultEntry.code = ErrorCodes.DATA_VALIDATE_FAILED;
            jsonResultEntry.msg = string.Join(",", msgs.Distinct());
        }


        public static void SetModelValidErrorMessage(this ApiJsonResultData jsonResultEntry, System.Web.Mvc.ModelStateDictionary dictionary)
        {
            List<string> msgs = new List<string>();
            foreach (var kv in dictionary)
            {
                foreach (var err in kv.Value.Errors)
                {
                    msgs.Add(err.ErrorMessage);
                }
            }
            jsonResultEntry.code = ErrorCodes.DATA_VALIDATE_FAILED;
            jsonResultEntry.msg = string.Join(",", msgs.Distinct());
        }


        public static ApiJsonResultData RunWithTry(this ApiJsonResultData jsonResultEntry, Action<ApiJsonResultData> runMethod, ILogger logger = null)
        {
            try
            {
                jsonResultEntry.SetCodeMsg(ErrorCodes.OK);
                runMethod.Invoke(jsonResultEntry);
            }
            catch (Exception ex)
            {
                jsonResultEntry.SetCodeMsg(ErrorCodes.SERVER_ERROR);
                jsonResultEntry.msg = ex.Message;
                if (Logger.IsNotNull())
                {
                    Logger.LogException($"RunWithTry Error, {System.Web.HttpContext.Current.Request.Url.AbsolutePath}", ex);
                }
            }
            return jsonResultEntry;
        }
    }
}
